package demo.hdz.mediacodecdecode.filter;

import android.content.Context;
import android.opengl.GLES11Ext;
import android.opengl.GLES20;

/**
 * @author hdz
 * @date 2022/05/28 21:59
 * <p>
 * 怀旧：https://www.daimajiaoliu.com/daima/569c39752625000
 */
public class NostalgicFilter extends BaseFilter {

    private final static float[] COLOR_MATRIX3 = {
            // 怀旧效果矩阵
            0.393f, 0.349f, 0.272f, 0.0f,
            0.769f, 0.686f, 0.534f, 0.0f,
            0.189f, 0.168f, 0.131f, 0.0f,
            0.0f, 0.0f, 0.0f, 1.0f
    };

    //顶点着色器坐标，z为0
    private static final float[] VERS = {
            -1.0f, -1.0f, 0.0f,
            1.0f, -1.0f, 0.0f,
            -1.0f, 1.0f, 0.0f,
            1.0f, 1.0f, 0.0f,
    };

    //纹理坐标，texture坐标ST，需要根据图像进行转换
    private static final float[] TXTS = {
            0.0f, 0.0f,
            1.0f, 0.0f,
            0.0f, 1.0f,
            1.0f, 1.0f
    };

    private int mSTMatrixHandle;
    private int mProgramHandle;

    public NostalgicFilter(Context context, String vPath, String fPath) {
        super(context, vPath, fPath);
    }

    @Override
    public void init() {
        int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, vShader.trim());
        int fragmentShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fShader.trim());
        mProgramHandle = linkProgram(vertexShader, fragmentShader);

        GLES20.glUseProgram(mProgramHandle);
        //转换矩阵
        mSTMatrixHandle = GLES20.glGetUniformLocation(mProgramHandle, "uSTMatrix");

        //设置顶点坐标和纹理坐标
        int apos = GLES20.glGetAttribLocation(mProgramHandle, "aPosition");
        GLES20.glEnableVertexAttribArray(apos);
        GLES20.glVertexAttribPointer(apos, 3, GLES20.GL_FLOAT, false, 12, createBuffer(VERS));

        int atex = GLES20.glGetAttribLocation(mProgramHandle, "aTexCoord");
        GLES20.glEnableVertexAttribArray(atex);
        GLES20.glVertexAttribPointer(atex, 2, GLES20.GL_FLOAT, false, 8, createBuffer(TXTS));

        //设置颜色效果
        int colorMatrixHandle = GLES20.glGetUniformLocation(mProgramHandle, "uColorMatrix");
        GLES20.glUniformMatrix4fv(colorMatrixHandle, 1, false, COLOR_MATRIX3, 0);
    }

    @Override
    public void drawFrame(int textureId, float[] transformMatrix) {
        // Select the program.
        GLES20.glUseProgram(mProgramHandle);

        // Set the texture.
        GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
        GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, textureId);

        //update st mat4
        GLES20.glUniformMatrix4fv(mSTMatrixHandle, 1, false, transformMatrix, 0);

        //draw
        GLES20.glDrawArrays(GLES20.GL_TRIANGLE_STRIP, 0, 4);

        GLES20.glBindTexture(GLES11Ext.GL_TEXTURE_EXTERNAL_OES, 0);
        GLES20.glUseProgram(0);
    }

    @Override
    public void release() {

    }
}
